//
//  ViewController.swift
//  day06
//
//  Created by 杨绍鑫 on 2018/9/11.
//  Copyright © 2018年 crcnet. All rights reserved.
//

import UIKit
import CoreLocation

class ViewController: UIViewController {

    var loactionManager : CLLocationManager!
    
    @IBOutlet weak var locationLable: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override var preferredStatusBarStyle : UIStatusBarStyle {
        return UIStatusBarStyle.lightContent
    }

    @IBAction func startButton(_ sender: Any) {
        self.loactionManager = CLLocationManager()
        self.loactionManager.delegate = self
        self.loactionManager.requestAlwaysAuthorization()
        self.loactionManager.desiredAccuracy = kCLLocationAccuracyBest
        self.loactionManager.startUpdatingLocation()
    }
    
}

extension ViewController : CLLocationManagerDelegate{
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        CLGeocoder().reverseGeocodeLocation(manager.location!) { (pmakr, erro) in
            if erro != nil {
                self.locationLable.text = "reverse fail:" + (erro?.localizedDescription)!
                return
            }
            if (pmakr?.count)! > 0{
                self.displayPmakr(pmakr![0])
            }
        }
    }
    
    func displayPmakr(_ pmakr:CLPlacemark?){
        self.loactionManager.stopUpdatingLocation()
        
        if let p = pmakr {
            let postcode = p.postalCode ?? ""
            let city = p.locality ?? ""
            
            let administrativeArea = p.administrativeArea ?? ""
            let country = p.country ?? ""
            
            self.locationLable.text = postcode + city + "\n" + administrativeArea + "，" + country
            self.locationLable.isOpaque = true
            
        }
    }
}
